package com.zz.framework.core.common

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStoreOwner
import com.zz.framework.core.base.BaseViewModel
import com.zz.framework.core.utils.LogUtils
import java.lang.reflect.Field

/**
 * Copyright © 2020 zanezhao All rights reserved.
 * Created by zanezhao on 2020/2/29 9:31 PM.
 * @author: zanezhao 1820022519@qq.com
 * @version: V1.0
 */
object ViewModelFactory {
    /**
     *  创建 对应的 ViewModel, 并且 添加 通用 SharedData (LiveData) 到 ViewModel中
     */
    fun createViewModel(fragment: Fragment,viewModelName: String?, field: Field,isSingle: Boolean): BaseViewModel<*> {
        val viewModel = realCreateViewModel(field, viewModelName,fragment,isSingle)
        return viewModel
    }

    /**
     *  创建 对应的 ViewModel, 并且 添加 通用 SharedData (LiveData) 到 ViewModel中
     */
    fun createViewModel(activity: FragmentActivity, viewModelName: String?,field: Field,isSingle: Boolean): BaseViewModel<*> {
        val viewModel = realCreateViewModel(field,viewModelName, activity,isSingle)
        return viewModel
    }

    @Suppress("UNCHECKED_CAST")
    private fun realCreateViewModel(field: Field,viewModelName: String?, owner: ViewModelStoreOwner,isSingle: Boolean): BaseViewModel<*> {
        val viewModelClass = field.genericType as Class<BaseViewModel<*>>
        var mViewModel =
            if (isSingle){
                viewModelName?.let { ViewModelProvider(owner).get(it, viewModelClass) }
            }else{
                ViewModelProvider(owner).get(viewModelClass)
            }
        LogUtils.error("-----------------A-----------------------")
        LogUtils.error("-A--modelClass:" + owner.javaClass.canonicalName + " viewModelName:" + viewModelName +  " obj:" + mViewModel?.toString())
        LogUtils.error("----------------------------------------")
        return mViewModel?:ViewModelProvider(owner).get(viewModelClass)
    }
}